const { searchRecord, addRecord, getItems, updateRecord } = require('../../utils/feishuAPI');
Page({
  data: {
    // 定义课前，课中，课后问题列表
    questionTypes: [
      {
        name:"before",
        tasks:[
          {title: '任务1： ************', checked: true },
          {title: '任务2： ************', checked: false },
        ]
      },
      {
        name:"middle",
        tasks:[
          {title: '任务1： ************', checked: true },
          {title: '任务2： ************', checked: false },
        ]
      },
      {
        name:"after",
        tasks:[
          {title: '任务1： ************', checked: true },
          {title: '任务2： ************', checked: false },
        ]
      }
    ],
    currentTasks:[
      {title: '任务1： ************', checked: true },
      {title: '任务2： ************', checked: false },
    ],
    currentType: 2,  // 当前显示的问题类型
    leftBtnDisabled: false,  // 是否禁用左边按钮
    rightBtnDisabled: true,  // 是否禁用右边按钮
    currentStage: 1,  // 初始阶段设置为1
    currentSeed: 1, // 当前火种
    goal: {}, // 课程目标 
    classGoal: '',
    organGoal: '',
  },

  onLoad: function () {
    
  },

  onShow: function () {
    // 页面加载时处理
    this.updateTasks()
    // 页面显示时更新标题
    console.log("current page: home");
    this.update()
  },

  // 获取任务
  updateTasks() {
    const app = getApp()
    const that = this
    const query = {
      filter: {
        "conjunction": "and",
        "conditions": [
          {
            "field_name": '周次',
            "operator": "is",
            "value": [
              app.globalData.week
            ]
          },
          {
            "field_name": '组号',
            "operator": "is",
            "value": [
              app.globalData.classInfo['组号']
            ]
          }
        ]
      }
    };
    searchRecord('任务管理表', query)
    .then((r) => {
      console.log('r:', r)
      
      if (r != 0) {
        record_id = []
        for (let i = 0; i < r.data.data.items.length; i++) {
          record_id[i] = r.data.data.items[i].record_id
        }
        console.log('record_id:', record_id)
        res = getItems('任务管理表', r.data.data.items)
        console.log(`update task(res):`, res)
        task1 = []
        task2 = []
        task3 = []
        for (let i = 0, i1 = 0, i2 = 0, i3 = 0; i < res.length; i++) {
          task = {
            "record_id": record_id[i],
            "title": res[i]['任务内容'],
            "checked": res[i]['是否完成'] == '未完成' ? false : true
          }
          console.log(`task[${i}]: `, task)
          if (res[i]['任务类别'] == '课前任务') {
            task1[i1++] = task
          } else if (res[i]['任务类别'] == '课中任务') {
            task2[i2++] = task
          } else if (res[i]['任务类别'] == '课后任务') {
            task3[i3++] = task
          }
        }
        console.log("task1: ", task1)
        console.log("task2: ", task2)
        console.log("task3: ", task3)

        that.setData({
          'questionTypes[0].tasks': task3,
          'questionTypes[1].tasks': task2,
          'questionTypes[2].tasks': task1, 
        })
        that.setData({
          currentTasks: that.data.questionTypes[that.data.currentType].tasks,
        })

        
        // 将任务信息缓存到本地
        tt.setStorage({
          key: 'tasks',
          data: that.data.questionTypes
        })
      
        that.calculateProgress()

        console.log('questionTypes:', that.data.questionTypes)
      } else {
        console.log('update tasks fail')
      }
    })
  },

  // 页面更新
  update() {
    const that = this
    const app = getApp()
    app.updateTitle()
    this.updateGoal()
    this.setData({
      currentStage: 2,
      currentSeed: 2,
    })
  },
  
  // 获取周次目标
  updateGoal: function() {
    const app = getApp()
    const that = this
    const query = {
      filter: {
        "conjunction": "and",
        "conditions": [
          {
            "field_name": '周次',
            "operator": "is",
            "value": [
              app.globalData.week
            ]
          },
          {
            "field_name": '组号',
            "operator": "is",
            "value": [
              app.globalData.classInfo['组号']
            ]
          }
        ]
      }
    };
    searchRecord('目标管理表', query)
    .then((res) => {
      
      if (res != 0) {
        r = getItems('目标管理表', res.data.data.items)
        app.globalData.goal = r[0]
        console.log(r)
        app.globalData.classGoal = r[0]['课程目标']
        app.globalData.organGoal = r[0]['组织目标']
        console.log(`home: update: app.globalData.isClassLogin:${app.globalData.isClassLogin}`)
        if (app.globalData.isClassLogin) {
          that.data.goal = app.globalData.goal
          that.data.classGoal = app.globalData.classGoal
          that.data.organGoal = app.globalData.organGoal
        }

        // 更新阶段
        that.setData({
          classGoal: app.globalData.classGoal,
          organGoal: app.globalData.organGoal,
        })
        console.log(`current stage: ${that.data.currentStage}`)
        console.log(`current seed: ${that.data.currentSeed}`)
        console.log(`classGoal:${that.data.classGoal}`)
        console.log(`organGoal:${that.data.organGoal}`)
      } else {
        console.log('search fail')
      }
    })
  },

  // 处理左按钮点击
  onLeftClick() {
    console.log('onLeftClicked:', this.data.questionTypes)
    if (this.data.leftBtnDisabled) return;  // 如果左边按钮被禁用，不做任何操作
    const currentType = this.data.currentType;
    if (currentType === 0) {
      return; // 最左边时无法左移
    }
    // 切换到前一个问题类型
    const newType = currentType === 1 ? 0 : 1;
    const that = this;
    this.setData({
      currentType: newType,
      currentTasks: that.data.questionTypes[newType].tasks,
      leftBtnDisabled: newType === 0, // 如果已经到最左边，禁用左按钮
      rightBtnDisabled: false,  // 恢复右边按钮可点击
    });

    // 更新任务勾选状态
    this.updateCheckedTasks(newType);
    console.log('onLeftClicked:', this.data.questionTypes)
  },

  // 处理右按钮点击
  onRightClick() {
    console.log('onRightClicked:', this.data.questionTypes)
    if (this.data.rightBtnDisabled) return;  // 如果右边按钮被禁用，不做任何操作
    const currentType = this.data.currentType;
    if (currentType === 2) {
      return; // 最右边时无法右移
    }
    // 切换到下一个问题类型
    const newType = currentType === 1 ? 2 : 1;
    // this.setData({
    //   currentType: newType,
    //   leftBtnDisabled: false,  // 恢复左边按钮可点击
    //   rightBtnDisabled: newType === 2, // 如果已经到最右边，禁用右按钮
    // });
    const updatedTasks = JSON.parse(JSON.stringify(this.data.questionTypes[newType].tasks));  // 深拷贝
    const that = this;
    this.setData({
      currentType: newType,
      currentTasks: that.data.questionTypes[newType].tasks,
      leftBtnDisabled: false,
      rightBtnDisabled: newType === 2,
      [`questionTypes[${newType}].tasks`]: updatedTasks  // 强制更新 tasks
    });

    // 更新任务勾选状态
    this.updateCheckedTasks(newType);
    console.log('onRightClicked:', this.data.questionTypes)
  },

  // 更新任务勾选状态
  updateCheckedTasks(newType) {
    // const currentType = this.data.currentType;
    // const currentTasks = this.data.questionTypes[currentType].tasks;
    const that = this

    // 传递勾选状态到新的任务类型
    // const updatedTasks = this.data.questionTypes[newType].tasks.map(item => {
    //   const existingTask = currentTasks.find(task => task.record_id === item.id);
    //   item.checked = existingTask ? existingTask.checked : false; // 保持勾选状态
    //   return item;
    // });
    // for(let i = 0; i < that.data.questionTypes[newType].tasks.length; i++){
    //   console.log(`questionTypes[${newType}].tasks[${i}].checked: `, that.data.questionTypes[newType].tasks[i].checked)
    //   this.setData({
    //     [`questionTypes[${newType}].tasks[${i}].checked`]: that.data.questionTypes[newType].tasks[i].checked
    //   });
    // }
    // tasks =  questionTypes[newType].tasks
    // this.setData({
    //   `questionTypes[${currentType}].tasks`: tasks
    // });
    
  },

  // 计算进度条宽度
  calculateProgress() {
    num = 0
    sum = 0
    const that = this
    for (let i = 0; i < 3; i++) {
      len = that.data.questionTypes[i].tasks.length
      sum += len
      for (let j = 0; j < len; j++) {
        if (that.data.questionTypes[i].tasks[j].checked) {
          num++
        }
      }
    }
    const progress = (num / sum) * 100;
    console.log(`num: ${num}  sum: ${sum}  progress: ${progress}`)

    // 更新进度条宽度
    this.setData({
      progressBarWidth: progress
    });
    const app = getApp()
    app.globalData.progress = progress
  },

  // 在任务更新时调用 calculateProgress
  onCheckboxChange(e) {
    const that = this
    console.log('onCheckBoxClicked: e:', e)
    console.log('onCheckBoxClicked:', this.data.questionTypes)
    console.log('record_id:', e.currentTarget.dataset.id)
    const id = e.currentTarget.dataset.id
    for (let i = 0; i < that.data.questionTypes.length; i++) {
      for (let j = 0; j < that.data.questionTypes[i].tasks.length; j++) {
        if (that.data.questionTypes[i].tasks[j].record_id == id) {
          console.log('that.data.questionTypes[i].tasks[j].checked:', that.data.questionTypes[i].tasks[j].checked)
          that.data.questionTypes[i].tasks[j].checked = that.data.questionTypes[i].tasks[j].checked == true ? false : true;
          // 上传
          yesOrNo = that.data.questionTypes[i].tasks[j].checked == true ? "已完成" : "未完成"
          updateRecord('任务管理表', id, { "是否完成" : yesOrNo})
        }
      }
    }
    this.setData({
      currentTasks: that.data.questionTypes[that.data.currentType].tasks,
    });
    // const checkedValues = e.detail.value;
    // const currentType = this.data.currentType;
    // 深拷贝并更新当前任务类型的勾选状态
    // const updatedQuestions = this.data.questionTypes[currentType].map(item => {
    //   item.checked = checkedValues.includes(item.id.toString());
    //   return item;
    // });
  
    // 更新数据并重新计算进度
    // this.setData({
    //   [`questionTypes.${currentType}`]: updatedQuestions,
    // });
  
    // 更新进度条
    this.calculateProgress();
    console.log('onCheckBoxClicked:', this.data.questionTypes)
  },

  // 上传成果
  onUpload() {
    tt.navigateTo({
      // url: `../upload/upload`,
      url: `/pages/uploadView/index?url=${encodeURIComponent(`https://byd3anf1gt.feishu.cn/share/base/form/shrcnSkzoMsMdU5AxFLVjyxFBOe`)}`,
      success: function(res){
         // 传递数据
      },
    });

  },

  // 处理火种点击事件
  handleSeedClick: function (event) {
    const seed = event.currentTarget.dataset.seed; // 获取点击的组件的编号
    if (this.data.currentSeed == seed) {
      // 如果点击的是当前重要的组件，处理事件
      wx.showToast({
        title: `点击了火种${seed}`,
        icon: 'success',
      });
    } else {
      // 如果点击的不是当前重要的组件，不做处理
      console.log(`火种${seed}不可点击`);
    }
  },

  // 切换小组
  onGroupSelectClick() {
    tt.showToast({
      "title": "切换结伴组",
      "duration": 1000,
      "icon": "success",
      success(res) {
        console.log(JSON.stringify(res));
      },
      fail(res) {
        console.log(`showToast fail: ${JSON.stringify(res)}`);
      }
    })
  },

  // 点击某个阶段时切换 currentStage
  onStageClick: function(event) {
    const stageIndex = event.currentTarget.dataset.index;  // 获取点击的阶段index
    this.setData({
      currentStage: stageIndex,  // 更新currentStage
    });
  },

  // 更新目标
  updateGoals() {
    const goal = this.data.goal
    const that = this
    console.log(`this class goal: ${goal['课程目标']}`)
    console.log(`this organ goal: ${goal['组织目标']}`)
    // 传递数据到详情页
    tt.removeStorage({
      key: 'currentGroupGoal', 
      success(res) {
          console.log('removeStorage success:', res);
      },
      fail(res) {
          console.error('removeStorage fail:', res);
      }
    });
    tt.setStorage({
      key: 'currentGroupGoal',
      data: {
        '课程目标': that.data.classGoal,
        '组织目标': that.data.organGoal
      }
    })
    tt.navigateTo({
      url: `../updateGoal/updateGoal?question=currentGroupGoal`,
      success: function(res){
      },
    });
  },

  onSevenSiClick: function(e) {
    tt.showToast({
      "title": "7私",
      "duration": 1000,
      "icon": "success",
      success(res) {
        console.log(JSON.stringify(res));
      },
      fail(res) {
        console.log(`showToast fail: ${JSON.stringify(res)}`);
      }
    })
  },
  onMaShiClick: function(e) {
    tt.showToast({
      "title": "码释",
      "duration": 1000,
      "icon": "success",
      success(res) {
        console.log(JSON.stringify(res));
      },
      fail(res) {
        console.log(`showToast fail: ${JSON.stringify(res)}`);
      }
    })
  },
  onThreeLanClick: function(e) {
    tt.showToast({
      "title": "三栏文档",
      "duration": 1000,
      "icon": "success",
      success(res) {
        console.log(JSON.stringify(res));
      },
      fail(res) {
        console.log(`showToast fail: ${JSON.stringify(res)}`);
      }
    })
  },
  onEightXMLClick: function(e) {
    tt.showToast({
      "title": "8XML文档",
      "duration": 1000,
      "icon": "success",
      success(res) {
        console.log(JSON.stringify(res));
      },
      fail(res) {
        console.log(`showToast fail: ${JSON.stringify(res)}`);
      }
    })
  },
  onOneQianClick: function(e) {
    tt.showToast({
      "title": "1牵引",
      "duration": 1000,
      "icon": "success",
      success(res) {
        console.log(JSON.stringify(res));
      },
      fail(res) {
        console.log(`showToast fail: ${JSON.stringify(res)}`);
      }
    })
  },
  onTwoGongClick: function(e) {
    tt.showToast({
      "title": "2公",
      "duration": 1000,
      "icon": "success",
      success(res) {
        console.log(JSON.stringify(res));
      },
      fail(res) {
        console.log(`showToast fail: ${JSON.stringify(res)}`);
      }
    })
  },
  onDivClick: function(e) {
    tt.showToast({
      "title": "除",
      "duration": 1000,
      "icon": "success",
      success(res) {
        console.log(JSON.stringify(res));
      },
      fail(res) {
        console.log(`showToast fail: ${JSON.stringify(res)}`);
      }
    })
  },
  onMulClick: function(e) {
    tt.showToast({
      "title": "乘",
      "duration": 1000,
      "icon": "success",
      success(res) {
        console.log(JSON.stringify(res));
      },
      fail(res) {
        console.log(`showToast fail: ${JSON.stringify(res)}`);
      }
    })
  },
  onAddClick: function(e) {
    tt.showToast({
      "title": "加",
      "duration": 1000,
      "icon": "success",
      success(res) {
        console.log(JSON.stringify(res));
      },
      fail(res) {
        console.log(`showToast fail: ${JSON.stringify(res)}`);
      }
    })
  },
});
